/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  DatePicker,
  Form,
  Icon,
  Input, InputNumber,
  message,
  Modal,
  notification,
  Popconfirm,
  Select,
  Table,
  Upload
} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalSelectMaterial from "./ModalSelectMaterial";
import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import notify from "../../../components/NotificationExtra";

const _ = require('lodash');
const {Option} = Select;
moment.locale('zh-cn');

@Form.create()
@connect(({
            user,
            global,
            dict,
            procure,
            vendor
          }) => ({...user, ...procure, ...dict, ...global, ...vendor}))
export default class ModalCreateOrEditRentProcureOrder extends FormBase {
  constructor(props) {
    super(props);
    const {values = {}} = this.props;
    this.state = {...values};
  }

  componentDidMount() {
    const {values = {}, dispatch} = this.props;
    const {code} = values;
    code && dispatch({
      type: 'procure/findOne',
      payload: {code}
    });
    dispatch && dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
    !code && dispatch({
      type: 'procure/clearOrder',
      payload: {code}
    });

    dispatch({
      type: 'procure/findMaterialRecordByOrderCodeMany',
      payload: {procureOrderCode: code}
    });
  }


  renderFoot = () => {
    const {foot, value, modalRef, callback, refresh, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              let {materialRecords = []} = this.props;
              const {materials = materialRecords} = this.state;

              _.merge(this.state, values);
              let amount = 0, count = 0;
              _.map(materials, item => {
                amount += item.price * item.count;
                count += item.count;
              });
              this.state.materials = materials;
              this.state.amount = amount;
              this.state.count = count;
              console.log(this.state);
              callback(this.state);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            refresh();
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };


  getVendorOpt = (list) => {
    return list.map(opt => (<Option key={opt.code} value={opt.name} label={opt}>
        {opt.name}
      </Option>
    ));
  };
  onVendorSelect = (value, option) => {
    const {props} = option;
    this.state.vendorBody = props.label;
    this.state.vendorCode = props.label.code;
  };

  cols = () => {
    return [
      {
        title: "物料", dataIndex: 'name', key: 'name', render: (value, record) => {
          const {code} = record;
          return this.getProductionElement(code, value);
        }
      },
      {title: "形态", key: "subcategory", dataIndex: "subcategory"},
      {title: "物料规格", key: "spec", dataIndex: "spec"},
      {title: "物料类型", key: "type", dataIndex: "type"},
      {title: "物料型号", key: "number", dataIndex: "number"},
      {title: "税率", key: "taxRate", dataIndex: "taxRate"},
      {title: "含税单价", key: "price", dataIndex: "price"},
      {title: "采购数量", key: "count", dataIndex: "count"},
      {
        title: "占用数量", key: "useCount", dataIndex: "useCount", render: value => {
          return <div>{value ? value : 0}</div>;
        }
      },
      {
        title: "可用数量", key: "useCount", dataIndex: "useCount", render: (value, option) => {
          const {count = 0, useCount = 0} = option;
          const color = useCount > count || useCount === count ? "#f22" : "#22f";
          return <div style={{color}}>{count - useCount}</div>;
        }
      },
      {title: "运费", key: "shippingFee", dataIndex: "shippingFee"},
      {title: "去向", key: "target", dataIndex: "target"},

      {
        title: "操作", key: "opt", dataIndex: "opt", render: (value, record) => {
          return <span>
                      {<a style={{marginRight: '6px'}}
                          onClick={() => {
                            this.onAddMaterial(record);
                          }}>编辑</a>}
            {
              <Popconfirm
                title="确认删除"
                onConfirm={() => {
                  const {pmLotId, useCount = 0} = record;
                  if (useCount > 0) {
                    notify({type: 'error', message: "物料已有订单占用，请修改订单后再删除！"});
                    return;
                  }
                  const {materials = []} = this.state;
                  _.remove(materials, item => {
                    return item.pmLotId === pmLotId;
                  });
                  console.log('deletee', materials);
                  const temp = this.state;
                  temp.materials = materials;
                  this.setState({...temp});

                }}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>删除</a>
              </Popconfirm>
            }
            </span>;
        }
      }
    ];
  };
  onAddMaterial = (values) => {
    const title = values ? "编辑物料" : "选择物料";

    ModalView.open(ModalSelectMaterial, {
      title,
      width: '1080px'
    }, {
      values,
      callback: materialBody => {
        let {materialRecords = []} = this.props;
        const {materials = materialRecords} = this.state;
        console.log('mater pmlotid', materialBody.pmLotId);
        if (values) {
          materials.forEach((item, index) => {
            console.log(item.pmLotId, values.pmLotId);
            if (item.pmLotId === values.pmLotId) {
              materials[index] = materialBody;
            }
          });
        } else {
          materials.push(materialBody);
        }
        this.state.materials = materials;
        console.log('this.state.mm', this.state);
        const temp = this.state;
        this.setState({...temp});
      }
    });
  };
  picHandlePreview = async file => {

    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    const temp = this.state;

    temp['previewImage'] = file.url || file.preview;
    temp['previewVisible'] = true;
    this.setState({...temp});
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };

  render() {
    let {form, footDisabled, style, vendors = [], divisionDict = [], materialRecords = [], cols = 2} = this.props;
    const model = this.props['ProcureOrderModel'];
    const {options} = model.materialType;
    const {
      code = "PRO" + moment().format('YYYYMMDDHHmmss'),
       materialType = "主营业务采购", taxRate = '13%',rentStartDate,rentEndDate,
      previewVisible,
      previewImage,
      materials = materialRecords,
      vendor,
      fileList = [],
      pdfFileList = [],shippingFee,shippingMan,
      division = divisionDict.length ? divisionDict[0].name : ""
    } = this.state;

    const {tenant} = this.getLoginInfo();
    const {tenantCode} = tenant;


    return (
      <div style={{...style}}>
        {<FormLayout form={form} cols={cols}>
          <FormField
            label={'采购单编码'}
            name={'code'}
            initialValue={code}
            required={true}
          >
            <Input disabled style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'采购单位'}
            name={'division'}
            initialValue={division}
            required={true}
          >
            <Select allowClear placeholder="请选择" style={{width: '100%'}}
                    onChange={value => {
                      this.state.division = value;
                    }}
            >
              {this.getDivision(divisionDict)}
            </Select>
          </FormField>
          <FormField
            label={'物料类型'}
            name={'materialType'}
            initialValue={materialType}
            required={true}
          >
            <Select allowClear placeholder="请选择" style={{width: '100%'}}
                    onChange={value => {
                      this.state.materialType = value;
                    }}
            >
              {this.getSelectOption(options)}
            </Select>
          </FormField>
          <FormField
            label={'税率'}
            name={'taxRate'}
            required={true}
            initialValue={taxRate}
          >
            <Select allowClear style={{width: '100%'}}>
              {this.getSelectOption(this.taxRateOption)}
            </Select>
          </FormField>
          <FormField
            label={'供应商'}
            name={'vendor'}
            initialValue={vendor}
            required={true}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getVendorOpt(vendors)}
                          filterOption={(inputValue, option) =>
                            option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                          }
                          allowClear
                          onSelect={this.onVendorSelect}
            >
              <Input
                suffix={
                  <Button
                    style={{marginRight: -12, zIndex: 100}}

                    type="primary"
                    onClick={() => {
                      window.open('#/procure/vendor');
                    }}
                  >
                    新建
                  </Button>
                }
              />
            </AutoComplete>
          </FormField>
          <FormField
            label={'租用开始日期'}
            name={'rentStartDate'}
            required={true}
            initialValue={rentStartDate ? moment(rentStartDate) : moment()}
          >
            <DatePicker style={{width: '100%'}}></DatePicker>
          </FormField>
          <FormField
            label={'租用结束日期'}
            name={'rentEndDate'}
            required={true}
            initialValue={rentEndDate ? moment(rentEndDate) : undefined}
          >
            <DatePicker style={{width: '100%'}}></DatePicker>
          </FormField>
          <FormField
            label={'承运人'}
            name={'shippingMan'}
            initialValue={shippingMan}
          >
            <Input  style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'运费'}
            name={'shippingFee'}
            initialValue={shippingFee}
          >
            <InputNumber  style={{width: '100%'}}></InputNumber>
          </FormField>
        </FormLayout>}
        <ViewTitle title={`物料列表`}
                   level={1}
                   actions={[
                     <Button type="primary" onClick={() => this.onAddMaterial()}>添加</Button>]}
        ></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.cols()}
          dataSource={materials}
          scroll={{x: true}}
          pagination={{pageSize: 100}}
          //scroll={{ x: 1300 }}
        ></Table>

        <ViewTitle
          title={'附件'}
        ></ViewTitle>
        {
          //上传图片
          <div style={{marginLeft: '64px'}}>
            <Upload
              action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
              listType="picture-card"
              fileList={fileList}
              accept={".png,.jpg"}
              onPreview={this.picHandlePreview}
              onChange={this.picHandleChange}
              onDownload={file => {
                console.log('ondownlad', file);
              }}
              beforeUpload={(file, fileList) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  notify({type: 'error', message: '文件过大！'});
                  return isLt2M;
                }
                return false;
              }}
            >
              {this.getUploadPicButton()}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={() => this.setState({previewVisible: false})}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </div>
        }
        {
          //上传PDF

          <div style={{marginLeft: '64px'}}>
            <Upload
              name={'file'}
              action={`http://127.0.0.1:18008/api/global/upload?orderCode=${code}&table=ProcureOrder&tenantCode=${tenantCode}&fileList=${[...pdfFileList]}`}
              headers={{authorization: 'authorization-text'}}
              listType={"picture-card"}
              accept={".pdf"}
              fileList={pdfFileList}
              showUploadList={true}
              // previewFile={file=>{
              //   console.log(file);
              // }}
              onDownload={info => {
                console.log('ondownlad', info);
              }}
              onPreview={this.pdfHandlePreview}
              onChange={(info) => {
                let {fileList} = info;
                fileList = fileList.filter(file => file.type === 'application/pdf');
                fileList = fileList.map(file => {
                  console.log('file response', file.response);
                  if (file.response) {
                    file.url = file.response.result.url; // 假设服务端返回了文件url
                  }
                  return file;
                });
                const temp = this.state;
                temp.pdfFileList = fileList;
                this.setState({...temp});

              }}
              // 限制文件类型为PDF
              beforeUpload={file => {
                const isPdf = file.type === 'application/pdf';
                if (!isPdf) {
                  message.error('只可以上传 PDF 文件!');
                }
                return isPdf;
              }}
            >
              {this.getUploadPdfButton()}
            </Upload>
          </div>}
        {!footDisabled && this.renderFoot()}
      </div>
    );
  }
}

